﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IPMS.Models;
using IPMS.Library;
using IPMS.Library.Constains;
using System.Web.Security;
using System.Web.Profile;
namespace IPMS.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/
        private UserModel userModel = new UserModel();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {


            return View();

        }
        //Post: admin/login
        [HttpPost]
        public ActionResult Login(string returnUrl)
        {
            string username = Request.Form["username"];
            string password = Request.Form["password"];


            if (!String.IsNullOrEmpty("username") && !String.IsNullOrEmpty(password))
            {
                string hashedPassword = UserLibrary.hashMD5Password(password);
                if (this.userModel.ValidateUser(username, hashedPassword))
                {
                    FormsAuthentication.SetAuthCookie(username, false);
                    if (returnUrl == null || returnUrl.Equals(""))
                    {
                        return RedirectToRoute("Dashboard");
                    }
                    else
                    {
                        return Redirect(returnUrl);
                    }

                }
                else
                {
                    ViewData["Error"] = Error.LOGIN_ERROR;
                    return View();
                }
            }
            else
            {
                ViewData["Error"] = "";
                if (String.IsNullOrEmpty("username"))
                {
                    ViewData["Error"] += Error.USERNAME_EXPECTED;
                }
                if (String.IsNullOrEmpty(password))
                {
                    ViewData["Error"] += Error.PASSWORD_EXPECTED;
                }
            }
            return View();
        }

        //GET Logout
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login");
        }
        //GET: List User /user/list
        [Authorize(Roles="Administrator")]
        public ActionResult List()
        {
            List<User> lstUser = this.userModel.GetAllUser();
            return View(lstUser);
        }
    }
}